<template>
  <div class="patient-list">
    <section>
      <el-row class="patient-list-info">
        <el-col :span="8">
          <el-card>
            <el-skeleton v-if="loading.info" animated />
            <el-row v-if="!loading.info" align="center" justify="end" type="flex">
              <div class="abbreviation">
                <span>当前阶段:</span>
                <span>{{ patientInfo.abbreviation }}</span>
              </div>
            </el-row>
            <el-row v-if="!loading.info" align="center" justify="center" style="margin-bottom: 15px" type="flex">
              <el-avatar :size="120" :src="patientInfo.avatarUrl" fit="cover">
                <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png">
              </el-avatar>
            </el-row>
            <el-row v-if="!loading.info" align="center" justify="center" type="flex">
              <div class="flex-column-align-center">
                <h2>{{ patientInfo.nickName }}</h2>
                <div>注册时间: {{ patientInfo.createTime }}</div>
              </div>
            </el-row>
          </el-card>
        </el-col>
        <el-col :span="16">
          <el-card>
            <el-row>
              <el-col :span="16">
                <h3>用户基本信息</h3>
              </el-col>
              <el-col :span="8">
                <el-row justify="end">
                  <el-col align="end">
                    <el-button type="danger" size="small" @click="clickOnDelete">删除</el-button>
                    <el-button size="small" @click="clickOnChangeGroup">修改组别</el-button>
                    <el-button size="small" @click="clickOnExport">导出档案</el-button>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

            <el-skeleton v-if="loading.info" animated />
            <el-descriptions v-else size="medium">
              <el-descriptions-item label="学校名称">{{
                patientInfo.school
              }}</el-descriptions-item>
              <el-descriptions-item label="学院">{{
                patientInfo.schoolName
              }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{
                patientInfo.phone
              }}</el-descriptions-item>
              <el-descriptions-item label="性别">
                <span v-if="patientInfo.sex === 1">男</span>
                <span v-if="patientInfo.sex === 2">女</span>
              </el-descriptions-item>
              <el-descriptions-item label="来源">{{
                patientInfo.createBy
              }}</el-descriptions-item>
              <el-descriptions-item label="邮箱">{{
                patientInfo.emaile
              }}</el-descriptions-item>

              <el-descriptions-item label="教练">{{
                patientInfo.coachName
              }}</el-descriptions-item>
              <el-descriptions-item label="生日">{{
                patientInfo.birthday
              }}</el-descriptions-item>
              <el-descriptions-item label="年龄">{{
                patientInfo.age
              }}</el-descriptions-item>
              <el-descriptions-item label="紧急联系人">{{
                patientInfo.emergencyContact
              }}</el-descriptions-item>
              <el-descriptions-item label="所属国家/地区">{{
                patientInfo.districtId
              }}</el-descriptions-item>
              <el-descriptions-item label="居住地址">{{
                patientInfo.districtId
              }}</el-descriptions-item>
              <el-descriptions-item label="课程时间">{{ patientInfo.courseTime }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-col>
      </el-row>
    </section>

    <section>
      <el-card class="patient-list-anxiety">
        <el-row class="patient-list-anxiety-table-header" justify="space-between" type="flex">
          <h3>焦虑记录</h3>

          <el-link :underline="false" type="primary" @click="clickOnCheckCycle">查看焦虑循环</el-link>
        </el-row>
        <el-row class="patient-list-anxiety-table">
          <patient-detail-table :type="0" />
        </el-row>
      </el-card>
    </section>

    <section>
      <el-card class="patient-list-relax">
        <el-row class="patient-list-relax-table-header">
          <h3>放松记录</h3>
        </el-row>
        <el-row class="patient-list-relax-table">
          <patient-detail-table :type="1" />
        </el-row>
      </el-card>
    </section>

    <section>
      <el-card class="patient-list-feeling">
        <el-row class="patient-list-feeling-table-header">
          <h3>心情记录</h3>
        </el-row>
        <el-row class="patient-list-feeling-table">
          <patient-detail-table :type="2" />
        </el-row>
      </el-card>
    </section>

    <section>
      <el-card class="patient-list-evaluation">
        <el-row class="patient-list-evaluation-table-header">
          <h3>测评记录</h3>
          <div class="evaluation-types flex-row-align-center">
            <div
              v-for="(item, index) in praticeList"
              :key="index"
              class="evaluation-type-item"
              @click="clickOnEvaluationType(item)"
            >
              <!--              <span style="margin-right: 10px">{{ getBehave(item.behaveType) }} ({{ item.count }})</span>-->
              <el-tag :type="item.behaveType === evaluationType ? 'success' : ''"><span>{{ item.behaveTypeStr }}</span>
                <span>({{ item.count }})</span></el-tag>
            </div>
          </div>
        </el-row>
        <el-row class="patient-list-evaluation-table">
          <patient-detail-table :evaluation-type="evaluationType" :type="3" />
        </el-row>
      </el-card>
    </section>

    <section>
      <el-card class="patient-list-evaluation">
        <el-row class="patient-list-evaluation-table-header">
          <h3>跟进记录</h3>
          <el-button v-if="!admin" size="mini" style="margin-left: 20px" type="primary" @click="addFollow()">
            添加跟进记录
          </el-button>
        </el-row>
        <el-row class="patient-list-evaluation-table">
          <patient-detail-table ref="followTable" :type="4" />
        </el-row>
      </el-card>
    </section>

    <!--    <el-dialog-->
    <!--      :visible.sync="followVisable"-->
    <!--      title="新增跟进记录"-->
    <!--      width="30%"-->
    <!--    >-->
    <!--      <el-form :inline="true" :model="formInline">-->
    <!--        <el-form-item label="姓名">-->
    <!--          <el-input v-model="formInline.operateBy" placeholder="请输入关键字" />-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="自杀风险等级">-->
    <!--          <el-radio-group v-model="formInline.riskLevel">-->
    <!--            <el-radio label="0">无风险</el-radio>-->
    <!--            >-->
    <!--            <el-radio label="1">低风险</el-radio>-->
    <!--            <el-radio label="2">中风险</el-radio>-->
    <!--            <el-radio label="3">高风险</el-radio>-->
    <!--          </el-radio-group>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="自杀风险等级描述">-->
    <!--          <el-input v-model="formInline.riskLevelDesc" placeholder="请输入关键字" type="textarea" />-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="上周作业情况">-->
    <!--          <el-radio-group v-model="formInline.weekWork">-->
    <!--            <el-radio label="0">超额完成</el-radio>-->
    <!--            <el-radio label="1">完成</el-radio>-->
    <!--            <el-radio label="2">部分完成</el-radio>-->
    <!--            <el-radio label="3">未完成</el-radio>-->
    <!--          </el-radio-group>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="上周作业情况描述">-->
    <!--          <el-input v-model="formInline.weekWorkDesc" placeholder="请输入关键字" type="textarea" />-->

    <!--        </el-form-item>-->
    <!--        <el-form-item label="来访者反馈">-->
    <!--          <el-input v-model="formInline.visitorsFeedback" placeholder="请输入关键字" type="textarea" />-->
    <!--        </el-form-item>-->
    <!--        <el-form-item>-->
    <!--          <el-button-->
    <!--            type="primary"-->
    <!--            @click="onSubmit"-->
    <!--          >保存-->
    <!--          </el-button>-->
    <!--        </el-form-item>-->
    <!--      </el-form>-->
    <!--    </el-dialog>-->

    <patient-follow-form-dialog
      v-if="followVisable"
      ref="dialog"
      @onClose="followVisable = false"
      @updated="onPatientFollowUpdate"
    />

    <patient-anxiety-cycle-dialog v-if="cycleVisiable" ref="cycleDialog" @close="cycleVisiable = false" />

    <el-dialog
      title="修改用户组别"
      :visible.sync="groupDialogVisible"
      width="30%"
      :before-close="handleGroupDialogClose"
    >

      <el-select v-model="groupSelected" placeholder="请选择用户组别">

        <el-option v-for="item in userGroupOptions" :key="item.label" :label="item.label" :value="item.value" />
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="groupDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmGroupChange">确 定</el-button>
      </span>
    </el-dialog>

  </div>

  <!--  <el-card>-->
  <!-- -->
  <!--  </el-card>-->
</template>

<script>
import { AddFollowList, GetPraticeList, GetUserDetail, DeleteUser, ChangeUserGroup, ExportPatients } from '@/api/api'
import { Message } from 'element-ui'
// import dayjs from 'dayjs'
import PatientDetailTable from '@/views/patient-detail/components/patientDetailTable'
import PatientFollowFormDialog from '@/views/patient-detail/components/patientFollowFormDialog'
import { mapGetters } from 'vuex'
import { getBehaveDisplayByType } from '@/utils/common'
import PatientAnxietyCycleDialog from '@/views/patient-detail/components/patientAnxietyCycleDialog.vue'

export default {
  name: 'PatientDetail',
  components: {
    PatientAnxietyCycleDialog,
    PatientFollowFormDialog,
    PatientDetailTable
  },
  data() {
    return {
      groupSelected: 0,
      groupDialogVisible: false,
      userId: 0,
      patientInfo: {
        userName: '',
        createTime: ''
      },
      avatarUrl: '',
      praticeList: [],
      followVisable: false,
      cycleVisiable: false,
      operateBy: '',
      createTime: '',
      formInline: {},

      evaluationType: 1,
      loading: {
        info: false
      },
      userGroupOptions: [
        {
          label: '教练组',
          value: 1
        },
        {
          label: '自助-有限组',
          value: 2
        }, {
          label: '自助-无限组',
          value: 3
        }, {
          label: '等待组',
          value: 4
        }
      ]
    }
  },
  computed: {
    ...mapGetters(['admin', 'userName']),
    visitedViews() {
      return this.$store.state.tagsView.visitedViews
    }

  },
  mounted() {
    this.reload()
  },
  methods: {
    reload() {
      const route = this.$route
      this.userId = Number.parseInt(route.query.id, 10)
      this.getUserDetail()
      this.getPraticeList()
    },
    handleGroupDialogClose(done) {
      done()
    },
    clickOnDelete() {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // this.$router.replace('/patient-list/index')
        this.requestDelete()
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // })
      })
    },

    clickOnChangeGroup() {
      this.groupDialogVisible = true
    },
    clickOnExport() {
      this.requestExport()
    },
    confirmGroupChange() {
      this.groupDialogVisible = false
      if (this.groupSelected > 0) {
        this.requestChangeGroup()
      }
    },

    async requestExport() {
      try {
        await ExportPatients({ ids: [this.userId] }, `${this.patientInfo.nickName}-档案数据`)
      } catch (e) {
        console.error(e)
      }
    },
    async requestDelete() {
      try {
        const { data } = await DeleteUser(this.userId)

        if (data.code !== 200) {
          this.$message({
            type: 'error',
            message: data.msg
          })
          return
        }

        // delete curent page in tagsview
        this.$router.replace('/patient-list/index')
        const idx = this.visitedViews.findIndex(item => {
          return item.path.includes('patient-detail')
        })
        this.$store.dispatch('tagsView/delView', this.visitedViews[idx]).then(({ visitedViews }) => {
        })

        this.$message({
          type: 'success',
          message: '删除成功'
        })
      } catch (e) {
        console.error(e.message)
      }
    },

    async requestChangeGroup() {
      try {
        const { data } = await ChangeUserGroup(this.userId, this.groupSelected)

        if (data.code !== 200) {
          this.$message({
            type: 'error',
            message: data.msg
          })
          return
        }

        this.$message({
          type: 'success',
          message: '修改成功'
        })
        this.reload()
      } catch (e) {
        console.error(e.message)
      }
    },

    onPatientFollowUpdate() {
      this.$refs.followTable.getFollowList()
    },

    async getUserDetail() {
      try {
        if (this.loading.info) {
          return
        }
        this.loading.info = true
        const { data } = await GetUserDetail(this.userId)
        this.loading.info = false

        // data.reserveStartTime ? data.reserveStartTime = dayjs(data.reserveStartTime).format('ddd hh:mm a') : undefined
        // data.reserveEndTime ? data.reserveEndTime = dayjs(data.reserveEndTime).format('ddd hh:mm a') : undefined
        // data.courseTime = data.reserveStartTime ? `${data.reserveStartTime} ~ ${data.reserveEndTime}` : '暂无课程时间信息'
        if (data.reserveList) {
          const firstReserve = data.reserveList[0]
          const date = new Date(firstReserve.reserveDate)
          data.courseTime = `每${this.$dayjs(date).format('ddd')} ${firstReserve.startTime
          } - ${firstReserve.endTime}`
        }
        this.patientInfo = data
        // handle group selected

        this.groupSelected = data.groupId
      } catch (e) {
        this.loading.info = false
        console.error(e)
      }
    },
    async getPraticeList() {
      try {
        if (this.loading.pratice) {
          return
        }
        this.loading.pratice = true
        const res = await GetPraticeList({ userId: this.userId })
        this.loading.pratice = false
        this.praticeList = [
          {
            behaveType: 1,
            behaveTypeStr: '全部',
            count: res.data.rows.reduce((total, item) => {
              return total + item.count
            }, 0)
          }
        ].concat(
          res.data.rows.map((item) => {
            item.behaveTypeStr = getBehaveDisplayByType(
              Number.parseInt(item.behaveType, 10)
            )
            return item
          })
        )
      } catch (e) {
        this.loading.pratice = false
        console.error(e)
      }
    },
    addFollow() {
      this.followVisable = true
      this.$nextTick(() => {
        this.$refs.dialog.visiable = true
      })
    },
    async onSubmit() {
      const params = {
        ...this.formInline,
        userId: this.userId
      }
      try {
        const res = await AddFollowList(params)
        Message.success(res.data.msg)
      } catch (e) {
        Message.error(e)
      }
      // this.getFollowList(this.$route.query.id)
      this.followVisable = false
      this.formInline = {}
    },

    clickOnEvaluationType(item) {
      this.evaluationType = item.behaveType
    },
    clickOnCheckCycle() {
      this.cycleVisiable = true
      this.$nextTick(() => {
        this.$refs.cycleDialog.visible = true
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.el-avatar {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.patient-list {
  background-color: #f9f9f9;
  padding: 20px;

  h3 {
    margin: 10px 0 15px 0;
  }

  .patient-list-info {
    .abbreviation {
      span {
        color: #999;

        &:last-child {
          color: red;
        }
      }
    }
  }

  section {
    margin-bottom: 15px;
  }

  &-info {
    margin-bottom: 50px;

    .el-col {
      &:first-child {
        padding-right: 15px;
      }

      .el-card {
        min-height: 280px;
      }
    }
  }

  &-anxiety {
    margin-bottom: 50px;
  }

  &-anxiety-table-header {
    //display: flex;
    //justify-content: space-around;
  }

  &-relax {
    margin-bottom: 50px;
  }

  &-relax-table-header {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 20px;
  }

  &-feeling {
    margin-bottom: 50px;
  }

  &-feeling-table-header {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 20px;
  }

  &-evaluation {
    margin-bottom: 50px;
  }

  &-evaluation-table-header {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    margin-bottom: 20px;

    .evaluation-types {
      margin-left: 10px;

      .evaluation-type-item {
        margin: 0 5px;
        cursor: pointer;

        span {
          font-size: 14px;
          color: #333333;

          &:last-child {
            color: red;
          }
        }
      }
    }
  }

  &-record {
    margin-bottom: 50px;
  }

  &-record-table-header {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 20px;
  }
}
</style>
